package cn.taobaoke.restful.domain;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.Collection;
import java.util.List;
import java.util.Optional;

/**
 * @author yangzuo
 * @since 2017-03-11
 */
public interface UserRepository extends JpaRepository<UserEntity, Long> {

    Optional<UserEntity> findByIdAndDomainId(Long id, Long domainId);

    List<UserEntity> findByDomainIdAndNameIn(Long domainId, Collection<String> names);

    Optional<UserEntity> findByWeChatAndDomainId(String weChat, Long domainId);

    @Query("from UserEntity user where user.name like %:keyword% or user.weChat like %:keyword% and user.domainId = :domainId")
    Page<UserEntity> findByKeyword(@Param("keyword") String keyword, Pageable pageable, @Param("domainId") Long domainId);

    @Query("FROM UserEntity u WHERE u.id IN (SELECT r.userId FROM UserGroupRelation r WHERE r.groupId = :id) and u.domainId = :domainId")
    List<UserEntity> findUsersInGroup(@Param("id") Long groupId, @Param("domainId") Long domainId);

    @Query(value = "select u.* from tb_user u where u.domain_id = :domainId and (u.name like %:keyword% or u.we_chat like %:keyword%) and u.id in "
            + "(select r2.user_id from tb_agent_group_relation r1 "
            + "left join tb_agent agent on (r1.agent_id = agent.id or r1.agent_id = agent.parent_id or r1.agent_id = agent.grand_parent_id ) "
            + "left join tb_wx_group wx on r1.group_id = wx.id "
            + "left join tb_user_group_relation r2 on wx.id = r2.group_id where (agent.id = :id or agent.parent_id = :id or agent.grand_parent_id = :id) ) "
            + "order by ?#{#pageable}", nativeQuery = true)
    Page<UserEntity> findPagingUsersForAgentById(@Param("keyword") String keyword, @Param("id") Long agentId, Pageable pageable, @Param("domainId") Long domainId);

}
